/**
 * 
 */
package com.kathez.util.commonutils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.InvalidPropertiesFormatException;
import java.util.Map;
import java.util.Properties;

/**
 * @author Balaji T
 *
 */
public class PropertyLoader {
	 
	private static final Map<String,Properties> propertiesMap = initialize();
	
	private static Map<String,Properties> initialize(){
		final Map<String,Properties> propertiesMap = new HashMap<String,Properties>();
		final Properties propertyFilesMap = loadPropertiesFromXML("propertyfiles.xml");
		for(Object prop : propertyFilesMap.keySet()){
			Properties property = loadPropertiesFromXML(propertyFilesMap.getProperty((String)prop)); 
			propertiesMap.put((String)prop, property);
		}
		return propertiesMap;
	}

	/**
	 * To load the properties object from xml file
	 * The XML file must be available inside resources folder
	 */
	public static Properties loadPropertiesFromXML(String xmlFileName) {
		InputStream stream = null;
		try{
			final Properties propertyFilesMap = new Properties();
			stream =  PropertyLoader.class.getResourceAsStream("/resources/"+xmlFileName);
			if(stream != null){
				propertyFilesMap.loadFromXML(stream);
				return propertyFilesMap;
			}
		}catch(FileNotFoundException fileNotFoundExp){
			System.err.println(fileNotFoundExp.getMessage());
		} catch (InvalidPropertiesFormatException invalidPropsExp) {
			System.err.println(invalidPropsExp.getMessage());
		} catch (IOException ioExecp) {
			System.err.println(ioExecp.getMessage());
		}finally{
			try {
				if(stream != null){
					stream.close();
				}				
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				stream = null;
			}
			
		}
		return null;
	}
	
	public static String getProperty(String propFileName, String key){
		String value = null;
		if(propFileName == null || key == null || propertiesMap == null)
			return null;
		Properties props = propertiesMap.get(propFileName);
		if(props != null)
			value = props.getProperty(key);
		return value;
	}
	
	public static String getProperty(String key){
		String value = null; 
		if(key == null || propertiesMap == null)
			return null;
		for(String propFileName : propertiesMap.keySet()){
			value = getProperty(propFileName,key);
			if(value != null)
				break;
		}
		return value;
	}

}
